package com.GLM.Viewer.Party;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.GLM.Viewer.R;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class CreateNewPartyContactViewActivity extends Activity {
	private final static int CONTACTS_LOADING = 111;
	private final static int CONTACTS_LOADED = 222;
	
	ListView contactListView;
	Map<Integer, ContactInfo> contactsInfoMap = new HashMap<Integer,ContactInfo>();
//	private List<Map<String, Object>> contactListItems = new ArrayList<Map<String,Object>>(); 
//	private String[] contactItemKeys = new String[]{"contactName"};
//	private int[] contactItemViews = new int[]{R.id.newparty_contact_name};
	ContactInfo conInfo;
	ContactsAdapter conAdapter;
	SimpleAdapter mAdapter;
	Button sendButton;
	Button gobackButton;
	private ProgressBar mProgressBar;
	Set<String> checkedIdsSet = new HashSet<String>();
	private String mMeetPlaceName;
	private String mMeetPlaceAddr;
	private String mMeetPlacePhone;
	private String mMeetTime;
	private int screenWidth;
	private int screenHeight;
	
	private final Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			switch (msg.what) {
			case CONTACTS_LOADING:
				thread = new Thread(new Runnable() {
					
					public void run() {
						// TODO Auto-generated method stub
						mProgressBar.setVisibility(View.VISIBLE);
						contactsInfoMap = getAllContactsInfos();
						if(contactsInfoMap.size()>0){
							conAdapter = new ContactsAdapter();
						}
						
						mHandler.sendEmptyMessage(CONTACTS_LOADED);
					}
				});
				thread.start();
				break;
			case CONTACTS_LOADED:
				mProgressBar.setVisibility(View.INVISIBLE);
				if(conAdapter != null ){
					contactListView.setAdapter(conAdapter);
					bindItemClick();
				}else{
					Paint paint = new Paint();
					paint.setTextSize(20);
					paint.setAntiAlias(true);
					String str = getString(R.string.newparty_tips_nocontacts);
					Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.glm_background);
					Canvas canvas = new Canvas(bitmap);
					canvas.drawText(str,screenWidth/2-str.length()*9 , screenHeight/2, paint);
					FrameLayout layout = (FrameLayout)findViewById(R.id.newparty_contact_layout);
					Drawable drawable = new BitmapDrawable(bitmap);
					layout.setBackgroundDrawable(drawable);
				}
				
				break;
				
			default:
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_newparty_contact);
		screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		screenHeight = getWindowManager().getDefaultDisplay().getHeight();
		Intent intent = getIntent();
		mMeetPlaceName = intent.getStringExtra("MeetingPlaceName");
		mMeetPlaceAddr = intent.getStringExtra("MeetingPlaceAddr");
		mMeetPlacePhone = intent.getStringExtra("MeetingPlacePhone");
		mMeetTime = intent.getStringExtra("MeetingTime");
		
		contactListView = (ListView) findViewById(R.id.newparty_contact_listview);
		mProgressBar = (ProgressBar) findViewById(R.id.contacts_progressbar);
		
		sendButton = (Button)findViewById(R.id.newparty_contact_send_button);
		gobackButton = (Button)findViewById(R.id.goback_newparty_contact_button);
		sendButton.setOnClickListener(clickListeners);
		gobackButton.setOnClickListener(clickListeners);
		mHandler.sendEmptyMessage(CONTACTS_LOADING);
		
	}

	public void bindItemClick(){
		contactListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long arg3) {
				// TODO Auto-generated method stub
				
				if(contactsInfoMap.size()>0){
				
					ImageView imageView = (ImageView) view.findViewById(R.id.newparty_choose_imageview);
					if(imageView.getVisibility() == View.VISIBLE){
						checkedIdsSet.remove(String.valueOf(position));
						imageView.setVisibility(View.INVISIBLE);
					}else{
						checkedIdsSet.add(String.valueOf(position));
						imageView.setVisibility(View.VISIBLE);
					}
					
				}
				
			}
		});
	}
	
	public OnClickListener clickListeners = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.newparty_contact_send_button:
				if(checkedIdsSet.size()>0){
					String smsnumbers ="";
					Iterator iterator = checkedIdsSet.iterator();
					while(iterator.hasNext()){
						int index = Integer.valueOf((String) iterator.next());
						smsnumbers += contactsInfoMap.get(index).getContNumber();
						smsnumbers += ";";
					}
					smsnumbers = smsnumbers.substring(0, smsnumbers.length() - 1);
					Intent smsIntent = new Intent(Intent.ACTION_VIEW);
					smsIntent.putExtra("address", smsnumbers); 
					String bodyInfo = String.format(getString(R.string.newparty_tips_sendSMS), mMeetTime,checkedIdsSet.size(),mMeetPlaceName,mMeetPlaceAddr,mMeetPlacePhone);
					
					smsIntent.putExtra("sms_body", bodyInfo);
					smsIntent.setType("vnd.android-dir/mms-sms");
					startActivity(smsIntent);
				}
				break;
			case R.id.goback_newparty_contact_button:
				finish();
				break;
			}
		}
	};
	
	public Map<Integer, ContactInfo> getAllContactsInfos() {
		Map<Integer, ContactInfo> infoMap = null;
		
		Cursor cursor;
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		String[] projection = new String[] { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME,
				ContactsContract.Contacts.HAS_PHONE_NUMBER };

		cursor = getContentResolver().query(uri, projection, null, null, null);

		if (cursor != null) {
			cursor.moveToFirst();
			try {
				if (infoMap == null)
					infoMap = new HashMap<Integer, ContactInfo>();
				int index = 0;
				while (cursor.moveToNext()) {
					String contactId = cursor.getString(0);
					String contactName = cursor.getString(1);
					String hasPhone = cursor.getString(2);
					String contactNumber = null;
					if (hasPhone.compareTo("1") == 0) {
						Cursor phones = getContentResolver()
								.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
										null,
										ContactsContract.CommonDataKinds.Phone.CONTACT_ID
												+ " = " + contactId, null, null);
						while (phones.moveToNext()) {
							contactNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
							conInfo = new ContactInfo(contactId, contactName,
									contactNumber);
							
							infoMap.put(index++, conInfo);
						}
						phones.close();
						
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			} finally {
				if (cursor != null && !cursor.isClosed())
					cursor.close();
				projection = null;
			}
		}

		return infoMap;
	}


	class ContactsAdapter extends BaseAdapter {

		public int getCount() {
			// TODO Auto-generated method stub
			
			return contactsInfoMap.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if(contactsInfoMap.size()>0){
				convertView = LayoutInflater.from(getApplicationContext())
							.inflate(R.layout.view_newparty_contact_item, null);
				TextView nameTextView = (TextView) convertView
							.findViewById(R.id.newparty_contact_name);
		
				nameTextView.setText(contactsInfoMap.get(position).getContName());
				
			}

			return convertView;
		}

	}

	private class ContactInfo {
		private String contName;
		private String contNumber;
		private String contactId;

		public ContactInfo(String contactId, String name, String number) {
			this.contactId = contactId;
			contName = name;
			contNumber = number;
		}

		public String getContactId() {
			return contactId;
		}

		public String getContName() {
			return contName;
		}


		public String getContNumber() {
			return contNumber;
		}


	}
}
